/**
 *  编辑页
 *
 * 作者 admin
 * 日期 2024-08-07 16:43:01
 */
layui.use(['jquery','febs', 'form', 'validate','table','upload','fileUpload'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        laydate = layui.laydate,
        form = layui.form,
        table = layui.table,
        fileUpload = layui.fileUpload,
        commonJS = layui.commonJS,
        $view = $('#reportRectifyRecord-edit'),
        $accidentType = $('div[name="accidentType"]'),
        $accidentLevel = $('div[name="accidentLevel"]'),
        // $jobOperation = $('div[name="jobOperation"]'),
        // $reasonType = $('div[name="reasonType"]'),
        $directReason = $view.find('#directReason'),
        $indirectionReason = $view.find('div[id="indirectionReason"]'),
        $rootReason = $view.find('div[id="rootReason"]'),
        $accidentShipType = $('div[name="accidentShipType"]'),
        $rectificationImplementer = $view.find("#rectificationImplementer"),
        validate = layui.validate,
        tableIns;
    let tenantId = POPUP_DATA.tenantId;
    let reportId = POPUP_DATA.reportId;
    let reportRectificationId = POPUP_DATA.reportRectificationId;
    let injuryUserTableData = [];
    let culpritUserTableData = [];
    let accidentReportFileList = [];
    let accidentSurveyFileList = [];
    let accidentReasonSurveyFileList = [];
    let rectifyAuditRecordList=[];
    let userList = [];
    let userNameList = [];

    initDictItemLabel_rectifyRecord();

    form.verify(validate);
    form.render();

    initFormValue();
    initInjuryUserTable();
    initCulpritUserTable();
    laydate.render({
        elem: "#rectificationDate",
        done: function (value, date) {},
        type: 'datetime'
    })

    fileUpload.render({
        elem:'#uploadBtn',
        url:ctx + 'accident/upload',
        type:'2',
        maxNum:5,
        defaultData: accidentReportRectificationData && accidentReportRectificationData.accidentReasonRectifyFileList ? accidentReportRectificationData.accidentReasonRectifyFileList:[],
        done:function(res){
        }
        ,error: function(){
            layer.msg("服务器异常")
        }
    })

    function initDictItemLabel_rectifyRecord(){
        // febs.initDictItemLabel($jobOperation,'SAFETY_JOB_OPERATION',accidentReportData.jobOperation);
        febs.initDictItemLabel($accidentType,'SAFETY_ACCIDENT_TYPE',accidentReportData.accidentType);
        febs.initDictItemLabel($accidentLevel,'SAFETY_ACCIDENT_LEVEL',accidentReportData.accidentLevel);
        // febs.initDictItemLabel($reasonType,'SAFETY_ACCIDENT_REASON',accidentReportRectificationData.reasonType);
        febs.initDictItemLabel($accidentShipType,'SAFETY_SHIP_TYPE',accidentReportData.accidentShipType);
        febs.initDictItemLabel($directReason,'SAFETY_ACCIDENT_DIRECT_REASON',accidentReportData.directReason);
        febs.initDictItemLabel($indirectionReason,'SAFETY_ACCIDENT_INDIRECTION_REASON',accidentReportData.indirectionReason);
        febs.initDictItemLabel($rootReason,'SAFETY_ACCIDENT_ROOT_REASON',accidentReportData.rootReason);
    }

    initRecordAuditTable();
    function initRecordAuditTable() {
        tableIns = febs.table.init({
            elem: $view.find("#rectifyAuditRecord"),
            id: 'rectifyAuditRecord',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'auditRealName', title: '审核人姓名', width: 150},
                {field: 'auditResult',align:'center', title: '审核结果', width: 100, templet: function (d) {
                        return d.auditResult =='1'?'审核通过':'审核退回';
                    }
                },
                {field: 'auditReason', title: '审核理由', minWidth: 260},
                {field: 'createdTime',align:'center', title: '审核时间', width: 180},
            ]],
            done: function(res, curr, count){
            },
            data:rectifyAuditRecordList
        });
    }
    function initFormValue() {
        if(accidentReportRectificationData){
            //整改审核记录
            if(accidentReportRectificationData.rectifyAuditRecordList && accidentReportRectificationData.rectifyAuditRecordList.length>0){
                rectifyAuditRecordList = accidentReportRectificationData.rectifyAuditRecordList;
            }
            //肇事人员
            culpritUserTableData = accidentReportData.culpritUserDataList;
            //事故原因调查附件
            // accidentReasonSurveyFileList = accidentReportRectificationData.accidentReasonSurveyFileList;
            // if(accidentReasonSurveyFileList && accidentReasonSurveyFileList.length>0){
            //     renderFile('#uploadReportReasonSurveyBtn',accidentReasonSurveyFileList);
            // }
            form.val("reportRectifyRecord-edit-form", {
                "reportRectificationId": accidentReportRectificationData.reportRectificationId,
                "tenantId": accidentReportRectificationData.tenantId,
                "reportId": accidentReportRectificationData.reportId,
                "directReason": accidentReportRectificationData.directReason,
                "indirectionReason": accidentReportRectificationData.indirectionReason,
                "reasonContent": accidentReportRectificationData.reasonContent,
                "surveyDate": accidentReportRectificationData.surveyDate,
                "rectificationFlg": accidentReportRectificationData.rectificationFlg,
                "rectificationStatus": accidentReportRectificationData.rectificationStatus,
                "rectificationOpinion": accidentReportRectificationData.rectificationOpinion,
                "rectificationDeadline": accidentReportRectificationData.rectificationDeadline,
                "rectificationMeasures": accidentReportRectificationData.rectificationMeasures,
                "rectificationUsers": accidentReportRectificationData.rectificationUsers,
                "rectificationDate": accidentReportRectificationData.rectificationDate,
                "rectificationAuditUserId": accidentReportRectificationData.rectificationAuditUserId,
                "rectificationAuditRealName": accidentReportRectificationData.rectificationAuditRealName,
                "rectificationAuditDate": accidentReportRectificationData.rectificationAuditDate,
                "rectificationAuditRemark": accidentReportRectificationData.rectificationAuditRemark,
                "cautionaryFlg": accidentReportRectificationData.cautionaryFlg,
                "rectifyAuditRecordList": accidentReportRectificationData.rectifyAuditRecordList,
            })
            if(accidentReportRectificationData.cautionaryFlg === '1'){
                $view.find('input[type=checkbox]').attr("checked","true");
            }else{
                $view.find('input[type=checkbox]').attr("checked","false");
            }
            console.log(accidentReportRectificationData.rectificationImplementer,'11')
            if(!commonJS.isEmpty(accidentReportRectificationData.rectificationImplementer)) {
                userNameList = accidentReportRectificationData.rectificationImplementer.split("、");
                let htl =``;
                userNameList.forEach((item,index) => {
                    htl += `<span name="correlation" class="tag" 
                                            data-id="${index}">${item}<span style="color: red;margin-left: 5px;cursor:pointer;" onclick="delTags1(this,'${index}')">x</span></span>`
                })
                $('.selectName').append(htl)
            }
        }
        if (accidentReportData) {
            //伤亡人员
            injuryUserTableData = accidentReportData.injuryUserDataList;
            //事故调查附件
            accidentSurveyFileList = accidentReportData.accidentSurveyFileList;
            if(accidentSurveyFileList && accidentSurveyFileList.length>0){
                renderFile('#uploadReportSurveyBtn',accidentSurveyFileList);
            }
            //事故上报附件
            accidentReportFileList = accidentReportData.accidentReportFileList;
            if(accidentReportFileList && accidentReportFileList.length>0){
                renderFile('#uploadReportBtn',accidentReportFileList);
            }
            if(accidentReportData.noticeDeptFlg === '1'){
                $("#noticeDeptDiv").show();
            }else{
                $("#noticeDeptDiv").hide();
            }
            form.render('checkbox');
        }
    }

    function renderFile(elem,fileList){
        fileUpload.render({
            elem:elem,
            url:ctx + 'accident/upload',
            type:'2',
            maxNum:5,
            isDetail:true,
            defaultData: fileList,
            done:function(res){
            }
            ,error: function(){
                layer.msg("服务器异常")
            }
        })
    }

    form.on('submit(reportRectifyRecord-edit-form-save)', function (data) {
        addOrUpdate(data.field,'保存');
        return false;
    });

    form.on('submit(reportRectifyRecord-edit-form-submit)', function (data) {
        data.field.rectificationStatus = '4';
        addOrUpdate(data.field,'提交');
        return false;
    });

    $rectificationImplementer.on('click', function () {
        febs.modal.open('整改部门及负责人选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:'0',
                multiple:true,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                if(selectData) {
                    let data = getSelectData()
                    let htl = ``;
                    if(userNameList.length > 0 && selectData) {
                        for (let i = 0; i < selectData.length; i++) {
                            var userArr = userNameList.filter(item => item === selectData[i].uname + '(' + selectData[i].userNo + ')');
                            if(userArr && userArr.length > 0) {
                                febs.alert.warn(selectData[i].uname + "已存在，请勿重复选择！");
                                return false;
                            }
                        }
                    }
                    if (data && data.length > 0) {
                        data.forEach((item, index) => {
                            userList.push(item);
                            userNameList.push(item.uname + '(' + item.userNo + ')')
                            htl += `<span name="correlation" class="tag" 
                                            data-id="${item.userId}" 
                                            data-uname="${item.uname}" 
                                            data-userName="${item.userName}" 
                                            data-userNo="${item.userNo}" 
                                            data-userDeptId="${item.deptId}" 
                                            data-userDeptName="${item.deptName}" 
                                            data-userPostId="${item.postId}" 
                                            data-userPostName="${item.postName}" >${item.uname}(${item.userNo})<span style="color: red;margin-left: 5px;cursor:pointer;" onclick="delTags(this)">x</span></span>`
                        })
                    } else {
                        htl += `<span name="correlation" class="tag" 
                                            data-id="${data.userId}" 
                                            data-uname="${data.uname}" 
                                            data-userName="${data.userName}" 
                                            data-userNo="${data.userNo}" 
                                            data-userDeptId="${data.deptId}" 
                                            data-userDeptName="${data.deptName}" 
                                            data-userPostId="${data.postId}" 
                                            data-userPostName="${data.postName}" >${data.uname}(${data.userNo})<span style="color: red;margin-left: 5px;cursor:pointer;" onclick="delTags(this)">x</span></span>`
                    }
                    $('.selectName').append(htl)
                }
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });

    window.delTags1 = function (data,index) {
        $(data).parent().remove();
        var index = $(data).parent().attr("data-id");
        userNameList.splice(index,1)
    }

    window.delTags = function (data) {
        $(data).parent().remove();
        var removeUserId = $(data).parent().attr("data-id");
        let tempArr = userList.filter(item => item.userId === removeUserId);
        userList = userList.filter(item => item.userId !== removeUserId);
        if(tempArr && tempArr.length > 0) {
            let str = tempArr[0].uname + '(' + tempArr[0].userNo + ')'
            for (let i = 0; i < userNameList.length; i++) {
                if(str === userNameList[i]){
                    userNameList.splice(i,1);
                    break;
                }
            }
        }
    }

    function initInjuryUserTable() {
        injuryUserTableIns = febs.table.init({
            elem: $view.find('#injuryUserTable'),
            id: 'injuryUserTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            editTrigger: 'dblclick',
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'userId', title: 'id',hide:true},
                {field: 'userName', title: 'userName',hide:true},
                {field: 'userNo', title: 'userNo',hide:true},
                {field: 'deptId', title: 'deptId',hide:true},
                {field: 'realName',align:'center', title: '姓名', minWidth: 100},
                {field: 'sex',align:'center', title: '性别',width: 60, templet: function (d) {
                        var flg = '';
                        switch (d.sex) {
                            case "0": {
                                flg = '<span>男</span>'
                                break;
                            }
                            case "1": {
                                flg = '<span>女</span>'
                                break;
                            }
                            case "2": {
                                flg = '<span>保密</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },
                {field: 'deptName',align:'center', title: '部门', minWidth: 150},
                {field: 'userType',align:'center', title: '用工形式', minWidth: 100, templet: function (d) {
                        var flg = '';
                        switch (d.userType) {
                            case "1": {
                                flg = '<span>本工</span>'
                                break;
                            }
                            case "2": {
                                flg = '<span>外包工</span>'
                                break;
                            }
                            case "3": {
                                flg = '<span>外协工</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },
                {field: 'userSeniority',align:'center', title: '工龄(年)', minWidth: 80},
                {field: 'userDegree',align:'center', title: '学历', minWidth: 80},
                {field: 'identificationNo',align:'center', title: '身份证号', minWidth: 240},
                {field: 'injuryLevel',align:'center',title: '伤害程度',minWidth: 160},
                {field: 'economyLoss',align:'center', title: '经济损失(元)', minWidth: 120}
            ]],
            done: function(res, curr, count){
            },
            data:injuryUserTableData
        });
    }

    function initCulpritUserTable() {
        culpritUserTableIns = febs.table.init({
            elem: $view.find('#culpritUserTable'),
            id: 'culpritUserTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            css: [ // 设置单元格样式
                // 取消默认的溢出隐藏，并设置适当高度
                '.layui-table-cell{height: 50px; line-height: 40px;}',
                '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                '.layui-table-cell select{height: 36px; padding: 0 5px;}'
            ].join(''),
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'userId', title: 'id',hide:true},
                {field: 'userName', title: 'userName',hide:true},
                {field: 'userNo', title: 'userNo',hide:true},
                {field: 'deptId', title: 'deptId',hide:true},
                {field: 'realName',align:'center', title: '姓名', width: 140},
                {field: 'workplace',align:'center', title: '工作单位', minWidth: 150,hide:true},
                {field: 'deptName',align:'center', title: '部门', minWidth: 150},
                {field: 'joinDate',align:'center', title: '入司时间', minWidth: 140},
                {field: 'userType',align:'center', title: '用工形式', width: 100, templet: function (d) {
                        var flg = '';
                        switch (d.userType) {
                            case "1": {
                                flg = '<span>本工</span>'
                                break;
                            }
                            case "2": {
                                flg = '<span>外包工</span>'
                                break;
                            }
                            case "3": {
                                flg = '<span>外协工</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },
                {field: 'userSeniority',align:'center', title: '工龄(年)', width: 120,hide:true},
                {field: 'currentSeniority',align:'center', title: '本工种工龄', width: 120},
                {field: 'userDegree',align:'center', title: '学历', width: 100},
                {field: 'identificationNo',align:'center', title: '身份证号', width: 170},
                {field: 'lossHours',align:'center', title: '损失工时', minWidth: 130},
            ]],
            done: function(res, curr, count){
            },
            data:culpritUserTableData
        });
    }

    window.downloadAlertsFile = function (_this) {
        let filePath = $(_this).attr("filePath");
        let fileName = $(_this).attr("fileName");
        let data = {
            filePath:filePath,
            fileName:fileName
        };
        febs.download(ctx + 'accidentFile/downloadFile', data, fileName);
    }

    function addOrUpdate(data,operation) {
        data.tenantId = tenantId;
        data.reportRectificationId = reportRectificationId;
        data.reportId = reportId;
        data.accidentReportRectificationFileList = getFileData($("#uploadBtn"));
        if(userNameList.length === 0) {
            febs.alert.warn("未选择整改人，请确认！");
            return false;
        }
        data.rectificationImplementer = userNameList.join("、");
        if (data.reportId && data.reportId.length > 0) {
            febs.modal.confirm(operation+'整改录入信息','确定'+operation+'整改录入信息？', function (index) {
                febs.postArray(ctx + 'accidentReport/rectifyRecord', data, function () {
                    layer.closeAll();
                    febs.alert.success(operation+'成功');
                    $('#febs-accidentReportRectify').find('#query').trigger('click');
                });
            });
        }
    }

    function getFileData(ele){
        var fileDatas = ele.find(".fileOne")
        var fileList = [];
        $.each(fileDatas,function (index, item){
            var data = {
                filePath: item.dataset.filepath,
                fileName: item.dataset.filename,
                smallPath: item.dataset.smallpath,
            }
            fileList.push(data);
        })
        return fileList;
    }


});